package com.jing.intellij.apama

import com.intellij.ide.util.projectWizard.ModuleBuilder
import com.intellij.openapi.module.ModuleType
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.vfs.*
import java.io.File
import java.nio.file.Path

/**
 * 创建工程的生命周期:
 * getAllBuilders:获取支持的工程类型
 * setName: 设置module的名称, 默认是工程名
 * setModuleFilePath: 设置module的*。iml文件
 * setContentEntryPath:
 * createProject: 创建工程
 * commit: 创建工程提交
 * commitModule: 创建module提交
 * createAndCommitIfNeeded
 * createModule
 *
 */
class ApamaModuleBuilder: ModuleBuilder() {

    override fun getModuleType(): ModuleType<*> = ApamaModuleType.INSTANCE

    override fun createProject(name: String?, path: String?): Project? {
        return super.createProject(name, path)
    }

    override fun setupRootModel(modifiableRootModel: ModifiableRootModel) {
        if (contentEntryPath == null) {
            return
        }
        val sourceFolderNames = listOf("monitors", "queries", "events")
        //对于single-module工程来说, 直接在以根目录为contentEntry
        val rootVFile = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(Path.of(contentEntryPath as String))
        if (rootVFile != null) {
            val contentEntry = modifiableRootModel.addContentEntry(rootVFile)
            //添加sourceFolder
            sourceFolderNames.forEach {
                val file = File(contentEntryPath, it)
                if (!file.exists()) {
                    file.mkdirs();
                }
                val sourceFolderVFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file)
                if (sourceFolderVFile != null) {
                    contentEntry.addSourceFolder(sourceFolderVFile, false)
                }
            }
        }
    }
}